package com.winit.openapi.gfs.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.gfs.spi.GfsOrderServices;
import com.winit.gfs.spi.vo.GfsOrder;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;

/**
 * 
 * Teapplix对接Controller
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * kang.wang 	1.0  		2018年3月27日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/teapplixOrder")
public class GfsTeapplixOrderController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(GfsTeapplixOrderController.class);

    @Resource
    private GfsOrderServices gfsOrderServices;

    @Value("${teapplixAPIToken}")
    public String APIToken;
    
    /**
     * 
     * 取消订单
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/cancel")
    @ResponseBody
    public String cancel(HttpServletRequest request) {

        String apiToken = request.getHeader("APIToken");
        // 1.验证授权
        if(!APIToken.equals(apiToken)){
            throw new ApiException(ErrorCode.API_AUTH_TOKEN_FIALD);
        }
        String inputStr = null;
        JSONArray jsonArr = null;
        try {
            inputStr = IOUtils.toString(request.getInputStream());
            JSONObject json = JSONObject.parseObject(inputStr);
            jsonArr = json.getJSONArray("Orders");
        } catch (Exception e) {
            logger.error("teapplixOrder.cancel Exp:",e);
            throw new ApiException(ErrorCode.ILLEGAL_JSON_STRING);
        }
        if(jsonArr != null && jsonArr.size() > 0){
            for(Object o:jsonArr){
                JSONObject orderJson = (JSONObject) o;
                String sellerOrderId = orderJson.getString("TxnId");
                GetByKeyCommand<String> command = new GetByKeyCommand<String>();
                command.setCtx(CommandContext.getContext());
                command.setSearchKey(sellerOrderId);
                GfsOrder gfsOrder = gfsOrderServices.queryOrderBySellerOrderId(command);
                String status = (gfsOrder == null)?null:gfsOrder.getStatus();
                // 2.校验订单
                if(gfsOrder != null && status.equals("WFD")){
                    // 3.取消发货
                    GetByKeyCommand<Long> orderIdCommand = new GetByKeyCommand<Long>();
                    orderIdCommand.setCtx(CommandContext.getContext());
                    orderIdCommand.setSearchKey(gfsOrder.getOrderId());
                    gfsOrderServices.cancelOrderByOrderId(orderIdCommand);
                    logger.info("teapplixOrder cancel,operate success,sellerOrderId[{}],status[{}]",sellerOrderId,status);
                }else{
                    logger.info("teapplixOrder cancel,order not match,sellerOrderId[{}],status[{}]",sellerOrderId,status);
                }
            }
        }
//        ResponseMsg responseMsg = new ResponseMsg();
//        String msg = SpringMessageLocator.getMessage(ErrorCode.SUCCESS, CommandContext.getContext().getLocale());
//        responseMsg.setMsg(msg);
//        return responseMsg;
        return inputStr;
    }

}
